package com.project.class3_31;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public Server(){
        try {
            //开启服务器，并开放8088端口
            ServerSocket serverSocket = new ServerSocket(8088);

            //监听端口，如果有客户端连接到服务器，会将连接信息封装成socket对象
            Socket socket = serverSocket.accept();
            //从socket中得到读取流，用于接收客户端发送的数据
            InputStream in = socket.getInputStream();
            //从socket中得到写入流，用于将数据发送到客户端
            OutputStream out = socket.getOutputStream();

            byte[] byteArray = new byte[1024];
            //将读取流数据读取到字节数组
            in.read(byteArray);

            //将字节数组封装成字符串
            String str = new String(byteArray).trim();
            System.out.println("客户端发送消息："+str);

            //向客户端发送数据
            out.write("欢迎光临".getBytes());
            //刷新流，将数据真正写入数据源
            out.flush();

            //关闭流
            out.close();
            in.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new Server();
    }
}
